package com.hkedou.yuanhuo.token;

import com.hkedou.yuanhuo.adminsystem.business.user.model.SysUser;
import com.hkedou.yuanhuo.shiro.redis.RedisTokenManager;
import com.hkedou.yuanhuo.shiro.redis.impl.RedisTokenManagerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    Logger logger= LoggerFactory.getLogger(TokenInterceptor.class);

    @Autowired
    RedisTokenManager redisTokenManager;

    /**
     * 返回true才能往下执行，返回false取消当前请求
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token=null;

        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie:cookies) {
                if("access_token".equals(cookie.getName())){
                    token=cookie.getValue();
                }
            }
        }

        logger.debug("------------token={}",token);

        if(token!=null){
            SysUser sysUser = redisTokenManager.tokenUser(token);
            RedisTokenManagerImpl.setUserValue("access_token",token);
            if(sysUser!=null){
                RedisTokenManagerImpl.setUserValue("loginid",sysUser.getLoginid());
                logger.debug("------------user.loginid={}",sysUser.getLoginid());
                return true;
            }
        }

        if(handler instanceof HandlerMethod){
            if(((HandlerMethod) handler).hasMethodAnnotation(Anon.class)){
                return true;
            }else{

            }
        }

        response.sendRedirect("/nologintips");
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

        logger.debug("-----------------{}","postHandle");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.debug("-----------------{}","afterCompletion");

    }
}
